package com.intel.factorytest.util;

import android.app.Activity;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import android.content.Context;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.os.SystemProperties;
import android.view.WindowManager;
import android.view.Window;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import com.intel.factorytest.util.LogUtils;
import android.util.Log;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Map;
import java.util.HashMap;

public class Util {
    private static final String TAG ="util"; 
    public static boolean isSpeakerTesting = false;
    public static boolean isEarpiecTesting = false;
    public static boolean isFrontCameraTesting = false;
    public static boolean isRearCameraTesting = false;    
    public static boolean isVibrateTesting = false;
    public static boolean isWifiTesting = false;
    public static boolean isBluetoothTesting = false;    
    public static boolean isGnssTesting = false;
    public static boolean isLTEBandTesting = false;

    
    public static boolean isFtmMode = false;
    public static String readSDConfigByLines(String fileName, int type) {
        Log.i(TAG, "readSDConfigByLines fileName = " + fileName);
        String result = "";
        if("".equals(fileName))return "";
        
        File file = new File(fileName + "/mat_test_case_config");
        if(1 == type) {
            file = new File(fileName + "/mat_test_case_config_for_pcba");

        }
        BufferedReader reader = null;
        if (!file.exists()) {
             
            fileName =  "/storage/" + fileName.substring(fileName.lastIndexOf("/") + 1);
            
            if(1 == type) {
                fileName = fileName + "/" + "mat_test_case_config_for_pcba";
                
            } else {
                fileName = fileName + "/" + "mat_test_case_config";
             }
            Log.i(TAG, "fileName = " + fileName);
            file = new File(fileName);
            if(file.exists()) {

            } else {
                Log.i(TAG, "read file " + fileName + " fail !");
                return "";
            }
                

        }

        try {
            Log.i(TAG, "read file by line, once one line：");
            reader = new BufferedReader(new FileReader(file));
            String tempString = null;
            int line = 1;        // valid line

            // line by line read, until null
            while ((tempString = reader.readLine()) != null) {
                // show line information
                Log.i(TAG, "line " + line + ": " + tempString);

                if (tempString.length() != 0 && tempString.contains("SCREEN_ORIENTATION_LANDSCAPE")) {
                    if(tempString.contains("//"))continue;
                    result = "SCREEN_ORIENTATION_LANDSCAPE";
                    break;
                } else if(tempString.length() != 0 && tempString.contains("SCREEN_ORIENTATION_PORTRAIT")) {
                    if(tempString.contains("//"))continue;
                    result = "SCREEN_ORIENTATION_PORTRAIT";
                    break;
                } else {
                    result = "";
                }
                line++;

            }

            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }
        return result;
    }

    /**
     * float保留2位小数
     * @param a
     * @return
     */
    @Deprecated
    public static float reserve2decimals(float a) {
        return (float)(Math.round(a*100))/100;
    }
    
    /**
     * 保留n位小数
     * 
     * @param a 操作数
     * @param num 小数位数
     * @return
     */
    public static float dealDecimals(float a, int num) {
        return (float) (Math.round(a * Math.pow(10, num)))
                / (int) Math.pow(10, num);
    }

    public static String getSystemProperties(String key, String defaultValue) {
        if (key == null)
            return null;
        String property = SystemProperties.get(key, defaultValue);
        LogUtils.logi(key + "=" + property);
        return property;
    }
    
    public static int getSystemIntProperties(String key, int defaultValue) {
        if (key == null)
            return -1;
        int property = SystemProperties.getInt(key, defaultValue);
        LogUtils.logi(key + "=" + property);
        return property;
    }


    public static Date getCurrentTime() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Date curDate = new Date(System.currentTimeMillis());//get current time
        String time = formatter.format(curDate);
        LogUtils.logi( "currentTime:" + time + ",data:" + curDate);
        return curDate;
    }

    public static void keepScreenOn(Activity context){
        context.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }

    public static void wakeUpAndKeepScreenOn(Activity context){
        WakeLock screenLock = ((PowerManager)context.getSystemService(context.POWER_SERVICE)).newWakeLock(
            PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "TAG");
        screenLock.acquire();
        keepScreenOn(context);
        screenLock.release();
    }

    public static void setWindowBrightness(Activity context,float brightness){
        Window window = context.getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.screenBrightness = brightness;
        window.setAttributes(lp);
    }

    public static void safeIsClose(FileInputStream fis) {
        if (fis != null) {
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace(); 
            }
        }
    }

    public static void safeOsClose(FileOutputStream fos) {
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace(); 
            }
        }
    }

    public static void safeBrClose(BufferedReader br) {
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace(); 
            }
        }
    }

    public static void safeBwClose(BufferedWriter bw) {
        if (bw != null) {
            try {
                bw.close();
            } catch (IOException e) {
                e.printStackTrace(); 
            }
        }
    }

    private final static  Map<String, String> pathCharWhiteList = new HashMap<String, String>();
    static{
        //path char white list
        String pathCharWhiteListResources = "abcdefghijklmnopqrstuvwxyz_123457890ABCDEFGHIJKLMNOPQRSTUVWXYZ./\\";
        if(pathCharWhiteListResources != null && pathCharWhiteListResources.trim().length() != 0) {
            for (int i = 0; i < pathCharWhiteListResources.length(); i++) {
                String c = String.valueOf(pathCharWhiteListResources.charAt(i));
                pathCharWhiteList.put(c,c);
            }
        }
    }

    public static String validFilePath(String filePath) {
        String temp = "";
        for (int i = 0; i < filePath.length(); i++) {

            String curStr = String.valueOf(filePath.charAt(i));
            String nextStr = null;
            try {
                nextStr = String.valueOf(filePath.charAt(i + 1));
            } catch (Exception e) {}

            String curListStr = pathCharWhiteList.get(curStr);
            if (curListStr != null && curStr == "\\") {
                String sysFileSeparator = File.separator;
                if (null != sysFileSeparator && sysFileSeparator.equals(curStr)) {
                    temp += curStr;
                }
            }else if(curListStr != null && (!".".equals(curStr))) {
                temp += curStr;
            } else if (curListStr!= null && (".".equals(curStr)) &&(!".".equals(nextStr)) && (!"\\".equals(nextStr)) && (!"/".equals(nextStr))) {
                temp += curStr;
            }
        }
        filePath = temp;
        return filePath;
    }
}
